package cn.edu.fzu.homemaking.common;

import java.nio.charset.StandardCharsets;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacAlgorithms;
import org.apache.commons.codec.digest.HmacUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author fangxin
 * @date 2022年11月16日
 */
public final class SignValidator {

    private static final Logger log      = LoggerFactory.getLogger(SignValidator.class);

    private static final int    ONE_HOUR = 1000 * 60 * 60;

    private final String        appSecret;
    private final int           appSecretLen;
    private final HmacUtils     hmacUtils;

    /** 返回 钉钉机器人的签名助手 **/
    public static SignValidator homeMakingInfo() {
        return new SignValidator("1FQ92_0vjPOvz6DSm72sIGtuzXvGfPKTlslAZoq_d27eDmgP9H0t4eooVOXx2qeF");
    }


    private SignValidator(String appSecret) {
        this.appSecret = appSecret;
        this.appSecretLen = appSecret.length();
        this.hmacUtils = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, appSecret.getBytes(StandardCharsets.UTF_8));
    }


    public boolean validate(String timestamp, String sign) {

        long t = 0L;
        try {
            t = Long.parseLong(timestamp);
        } catch (NumberFormatException e) {
            log.error(e.getMessage());
        }

        if (System.currentTimeMillis() - t > ONE_HOUR) {
            return false;
        }

        StringBuilder sb = new StringBuilder(appSecretLen + 1 + timestamp.length());
        sb.append(timestamp).append('\n').append(appSecret);

        return sign.equals(new String(Base64.encodeBase64(hmacUtils.hmac(sb.toString()))));
    }

}
